package com.cnswhy.cloud.server.iot.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSONObject;
import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.MiniAppType;
import com.cnswhy.cloud.server.common.entity.mq.UserInfoTokenMsg;
import com.cnswhy.cloud.server.core.entity.WxUserInfo;
import com.cnswhy.cloud.server.core.service.WxUserInfoService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import com.cnswhy.cloud.server.iot.config.CnswhyServerAppResourceServerConfigure;
import com.cnswhy.cloud.server.iot.dto.WxCode2SessionDTO;
import com.cnswhy.cloud.server.iot.dto.WxUserInfoDTO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j

@Api(tags = "微信小程序用户相关")
@Controller
@RequestMapping("/wxUser")
public class WxUserController {
    @Autowired
    RedisService redisService;
    @Autowired
    MessageService messageService;
    @ApiOperation(value = "查询openid", httpMethod = "GET")
    @ApiParam(name = "code", value = "微信Code")
    @RequestMapping(value = "/getOpenId", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public R<Object> getOpenId(HttpServletRequest request, String code){
        log.info("查询openid：{}", code);
        try {
            if(StringUtils.isBlank(code)){
                throw new BizException("微信Code不可为空");
            }
            WxMaJscode2SessionResult sessionResult = CnswhyServerAppResourceServerConfigure.getWxMaService().jsCode2SessionInfo(code);
            redisService.set("sessionResult" + sessionResult.getOpenid(), sessionResult);
            messageService.sendQueueByObject(AmqpExchange.ALIPAY_TOKEN_MESSAGE, UserInfoTokenMsg.builder()
                    .miniAppType(MiniAppType.WX)
                    .openId(sessionResult.getOpenid())
                    .unionId(sessionResult.getUnionid())
                    .sessionKey(sessionResult.getSessionKey()).build());
            WxUserInfo wxUserInfo = wxUserInfoService.getOne(Wraps.<WxUserInfo>lbQ().eq(WxUserInfo::getOpenId,sessionResult.getOpenid()));
            boolean loginFlag = false;
            if(StringUtils.isNotBlank(wxUserInfo.getNickName())){
                loginFlag = true;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("openid", sessionResult.getOpenid());
            jsonObject.put("loginFalg", loginFlag);
            return R.success(jsonObject);
        }  catch (BizException e) {
            return R.fail(e.getMessage());

        }  catch (WxErrorException e) {
            return R.fail(e.getError().getErrorMsg());
        }catch (Exception e) {
            e.printStackTrace();
            return R.fail("查询openid失败");
        }
    }
    @Autowired
    WxUserInfoService wxUserInfoService;
    @ApiOperation(value = "同步openId", httpMethod = "GET")
    @RequestMapping(value = "/login", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public R<Object> login(HttpServletRequest request, WxCode2SessionDTO wxCode2SessionDTO){
        log.info("同步openid：{}", wxCode2SessionDTO.toString());
        try {
            messageService.sendQueueByObject(AmqpExchange.ALIPAY_TOKEN_MESSAGE, UserInfoTokenMsg.builder()
                    .miniAppType(MiniAppType.WX)
                    .openId(wxCode2SessionDTO.getOpenid())
                    .unionId(wxCode2SessionDTO.getUnionid())
                    .sessionKey(wxCode2SessionDTO.getSessionKey()).build());
            /*WxUserInfo wxUserInfo = wxUserInfoService.getOne(Wraps.<WxUserInfo>lbQ().eq(WxUserInfo::getOpenId,wxUserInfoDTO.getOpenid()));
            if(wxUserInfo != null){
                wxUserInfo.setAvatarUrl(wxUserInfoDTO.getAvatarUrl());
                wxUserInfo.setCity(wxUserInfoDTO.getCity());
                wxUserInfo.setContry(wxUserInfoDTO.getCountry());
                wxUserInfo.setNickName(wxUserInfoDTO.getNickName());
                wxUserInfo.setGender(wxUserInfoDTO.getGender());
                wxUserInfo.setProvince(wxUserInfoDTO.getProvince());
                wxUserInfoService.updateById(wxUserInfo);
            }*/
            return R.success(true);
        }  catch (BizException e) {
            return R.fail(e.getMessage());

        }catch (Exception e) {
            e.printStackTrace();
            return R.fail("查询openid失败");
        }
    }

    @ApiOperation(value = "同步wx用户信息", httpMethod = "GET")
    @RequestMapping(value = "/syncUserInfo", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public R<Object> syncUserInfo(HttpServletRequest request, WxUserInfoDTO wxUserInfoDTO){
        log.info("查询openid：{}", wxUserInfoDTO.toString());
        try {
            WxUserInfo wxUserInfo = wxUserInfoService.getOne(Wraps.<WxUserInfo>lbQ().eq(WxUserInfo::getOpenId,wxUserInfoDTO.getOpenid()));
            if(wxUserInfo != null){
                wxUserInfo.setAvatarUrl(wxUserInfoDTO.getAvatarUrl());
                wxUserInfo.setCity(wxUserInfoDTO.getCity());
                wxUserInfo.setContry(wxUserInfoDTO.getCountry());
                wxUserInfo.setNickName(wxUserInfoDTO.getNickName());
                wxUserInfo.setGender(wxUserInfoDTO.getGender());
                wxUserInfo.setProvince(wxUserInfoDTO.getProvince());
                wxUserInfoService.updateById(wxUserInfo);
            }
            return R.success(true);
        }  catch (BizException e) {
            return R.fail(e.getMessage());

        }catch (Exception e) {
            e.printStackTrace();
            return R.fail("查询openid失败");
        }
    }


    @ApiOperation(value = "微信用户手机号信息解密", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "openId"),
            @ApiImplicitParam(name = "encryptedData", value = "encryptedData"),
            @ApiImplicitParam(name = "ivStr", value = "ivStr")
    })
    @RequestMapping(value = "/getPhone", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public R<Object> getPhone(HttpServletRequest request, String openId,String encryptedData,String ivStr){
        log.info("微信用户手机号信息解密：{} {} {}", openId,encryptedData,ivStr);
        RespVo vo = new RespVo();
        try {
            if(StringUtils.isBlank(openId)){
                throw new BizException("微信Code不可为空");
            }
            if(StringUtils.isBlank(encryptedData)){
                throw new BizException("encryptedData不可为空");
            }
            if(StringUtils.isBlank(ivStr)){
                throw new BizException("ivStr不可为空");
            }
            WxMaJscode2SessionResult jscode2SessionResult = (WxMaJscode2SessionResult)redisService.get("sessionResult" + openId);
            if(jscode2SessionResult == null){
                throw new BizException("该openId未找到");
            }
            WxMaPhoneNumberInfo p =CnswhyServerAppResourceServerConfigure.getWxMaService().getUserService().getPhoneNoInfo(jscode2SessionResult.getSessionKey(),encryptedData,ivStr);

            return R.success(p);
        }  catch (BizException e) {
            return R.fail(e.getMessage());
        }/*  catch (WxErrorException e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage(e.getError().getErrorMsg());
        }*/catch (Exception e) {
            return R.fail("微信用户手机号信息解密 失败");

        }
    }


}
